package com.example.demo.Controller;


import com.example.demo.Email.EmailInfo;
import com.example.demo.Email.SendEmailService;
import com.example.demo.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.Tools.SRandom;
import org.springframework.web.context.annotation.SessionScope;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/Email")
@RestController
@SessionScope
public class EmailController {     //注入对象
    @Autowired
    private SendEmailService sendEmailService; // 发件服务
    @Autowired
    private UserMapper userMapper;
    private SRandom sRandom;    // 验证码
    private EmailInfo emailInfo = new EmailInfo(); // 邮件信息
    private String EmailToUser; // 送信地址

    @RequestMapping(value = "/sendEmailRegisterVerificationCode",method = RequestMethod.POST) // 发送邮箱验证码
    @ResponseBody
    public String sendEmailRegister(HttpServletRequest request) { // 注册账号发送邮箱验证码
        EmailToUser = request.getParameter("emailAddress"); // 前端回传emailAddress
        Map<String, Object> map = new HashMap<>();
        map.put("userEmail", EmailToUser);
        if(!userMapper.selectByMap(map).isEmpty()){
            return "-1"; // 邮箱已注册
        }


        sRandom = new SRandom();
        emailInfo.setTo(EmailToUser);
        emailInfo.setSubject("您当前正在注册每日打卡");
        emailInfo.setContent("验证码为: "+sRandom.getOneToSix().toString()+" 请勿回复此邮件");
        sendEmailService.sendSimpleMail(emailInfo);

        return "1"; // 邮件已发送
    }

    @RequestMapping(value = "/sendEmailVerificationCode",method = RequestMethod.POST) // 发送邮箱验证码
    @ResponseBody
    public String sendEmailVerificationCode(HttpServletRequest request) { // 发送邮箱验证码
        EmailToUser = request.getParameter("emailAddress"); // 前端回传emailAddress

        sRandom = new SRandom();
        emailInfo.setTo(EmailToUser);
        emailInfo.setSubject("感谢您使用每日打卡！");
        emailInfo.setContent("您的验证码为: "+sRandom.getOneToSix().toString()+" 请勿回复此邮件");
        sendEmailService.sendSimpleMail(emailInfo);

        return "1"; // 邮件已发送
    }

    @RequestMapping(value = "/verificationEmail",method = RequestMethod.POST) //验证邮箱验证码
    @ResponseBody
    public String verificationEmail(HttpServletRequest request) {
        String verificationCode = request.getParameter("verificationCode");

        if(!verificationCode.equals(sRandom.getOneToSix().toString()))
            return "0"; // 验证码不正确

        if(sRandom.isOverdue())
            return "-1"; // 验证码已过期
        if(sRandom.isUsed())
            return "-2"; // 验证码已被使用

        sRandom.setUsed(true);
        return "1"; // 通过验证

    }
}
